package com.hnas.ecard.dao.impl;

import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.persistence.Query;

import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Component;

import com.hnas.core.dao.BaseDaoImpl;
import com.hnas.core.util.DateUtil;
import com.hnas.core.util.StringUtil;
import com.hnas.ecard.dao.CommoditOrderDetailDao;
import com.hnas.ecard.domain.CommoditOrderStatus;
import com.hnas.ecard.orm.CommoditOrderDetail;
import com.hnas.ecard.service.dto.DTOCommoditOrder;
import com.hnas.ecard.service.dto.DTOCommoditOrderDetail;

@Component("commoditOrderDetailDao")
public class CommoditOrderDetailDaoImpl extends BaseDaoImpl<CommoditOrderDetail> implements CommoditOrderDetailDao{

	public CommoditOrderDetailDaoImpl() {
		super(CommoditOrderDetail.class);
	}

	@Override
	public CommoditOrderDetail saveOrUpdate(CommoditOrderDetail vo) {
		CommoditOrderDetail temp = null;
		if(null != vo){
			if(StringUtil.isNotEmpty(vo.getId())){
				temp = this.find(vo.getId());
			}
			if(null == temp){
				temp = vo;
				temp.setCreateTime(DateUtil.dateTimeToString(new Date()));
				temp.setUpdateTime(DateUtil.dateTimeToString(new Date()));
				temp.setIsDeleted(false);
				this.persist(temp);
			}else{
				BeanUtils.copyProperties(vo, temp,new String[]{"id", "createTime"});
				temp.setUpdateTime(DateUtil.dateTimeToString(new Date()));
				this.merge(temp);
			}
		}
		return temp;
	}

	@Override
	public CommoditOrderDetail findByOrderNo(String orderNo) {
		String hql = " from CommoditOrderDetail t where t.orderNo = ?1";
		Query query = this.entityManager.createQuery(hql);
		query.setParameter(1, orderNo);
		List<CommoditOrderDetail> resultList = query.getResultList();
		if(resultList != null && resultList.size() > 0) {
			return resultList.get(0);
		}
		return null;
	}


	@Override
	public List<DTOCommoditOrder> findOrderListByAccId(String accId) {
		if(StringUtil.isEmpty(accId)) return null;
		StringBuilder sb = queryOrderSql();
		sb.append(" from m_base_wxxnk_order t1,tbl_commodit_order_detail t2 where t1.order_no = t2.order_no and t1.acc_id = ?1 order by t1.create_time desc");
		Query query = this.entityManager.createNativeQuery(sb.toString());
		query.setParameter(1, accId);
		List<Object[]> resultList = query.getResultList();
		if(resultList != null && resultList.size() > 0) {
			List<DTOCommoditOrder> list = new ArrayList<DTOCommoditOrder>();
			for(Object[] result:resultList) {
				DTOCommoditOrder dto = assembleDTOCommoditOrder(result);
				list.add(dto);
			}
			return list;
		}
		return null;
		
	}
	
	private StringBuilder queryOrderSql() {
		StringBuilder sb = new StringBuilder();
		sb.append("select t1.id,")
		.append("t1.order_no,")
		.append("t1.order_type,")
		.append("t1.order_type_name,")
		.append("t1.acc_id,")
		.append("t1.acc_name,")
		.append("t1.order_detail,")
		.append("t1.order_status,")
		.append("t1.payment,")
		.append("t1.pay_status,")
		.append("t1.need_pay,")
		.append("t1.real_pay,")
		.append("t1.trade_type,")
		.append("t1.swift_number,")
		.append("t1.commidity_id,")
		.append("t1.commidity_type,")
		.append("t1.commidity_name,")
		.append("t1.card_no,")
		.append("t1.mrch_id,")
		.append("t1.mrch_name,")
		.append("t1.mrch_type,")
		.append("t1.psam_id,")
		.append("t1.sub_id,")
		.append("t1.trade_sno,")
		.append("t1.trade_end_time,")
		.append("t1.pay_end_time,")
		.append("t1.cancel_time,")
		.append("t1.create_time,")
		.append("t1.update_time,")
		.append("t1.creator,")
		.append("t1.updater,")
		.append("t1.is_deleted,")
		.append("t1.remark,")
		.append("t1.order_parent_type,")
		.append("t1.term_no,")
		.append("t2.state");
		return sb;
	}
	
	private DTOCommoditOrder assembleDTOCommoditOrder(Object[] result) {
		DTOCommoditOrder dto = new DTOCommoditOrder();
		dto.setId(String.valueOf(result[0]));
		dto.setOrderNo(String.valueOf(result[1]));
		dto.setOrderType(String.valueOf(result[2]));
		dto.setOrderTypeName(String.valueOf(result[3]));
		dto.setAccId(String.valueOf(result[4]));
		dto.setAccName(String.valueOf(result[5]));
		dto.setOrderDetail(String.valueOf(result[6]));
		dto.setOrderStatus(String.valueOf(result[7]));
		dto.setPayment(String.valueOf(result[8]));
		dto.setPayStatus(String.valueOf(result[9]));
		dto.setNeedPay(((BigInteger)result[10]).longValue());
		dto.setRealPay(((BigInteger)result[11]).longValue());
		dto.setTradeType(String.valueOf(result[12]));
		dto.setSwiftNumber(String.valueOf(result[13]));
		dto.setCommidityId(String.valueOf(result[14]));
		dto.setCommidityName(String.valueOf(result[15]));
		dto.setCommidityType(String.valueOf(result[16]));
		dto.setCardNo(String.valueOf(result[17]));
		dto.setMrchId(String.valueOf(result[18]));
		dto.setMrchName(String.valueOf(result[19]));
		dto.setMrchType(String.valueOf(result[20]));
		dto.setPsamId(String.valueOf(result[21]));
		dto.setSubId(String.valueOf(result[22]));
		dto.setTradeSno(String.valueOf(result[23]));
		dto.setTradeEndTime(String.valueOf(result[24]));
		dto.setPayEndTime(String.valueOf(result[25]));
		dto.setCancelTime(String.valueOf(result[26]));
		dto.setCreateTime(String.valueOf(result[27]));
		dto.setUpdateTime(String.valueOf(result[28]));
		dto.setCreator(String.valueOf(result[29]));
		dto.setUpdater(String.valueOf(result[30]));
		dto.setIsDeleted((Boolean)result[31]);
		dto.setRemark(String.valueOf(result[32]));
		dto.setOrderParentType(String.valueOf(result[33]));
		dto.setTermNo(String.valueOf(result[34]));
		dto.setState(Integer.valueOf(String.valueOf(result[35])));
		return dto;
	}

	@Override
	public List<DTOCommoditOrderDetail> listByOrderNo(String orderNo) {
		String hql = "select t1.mrch_id,t2.mrch_name,t1.term_no,t1.term_sno,t1.state,t1.update_time,t1.order_no from tbl_commodit_order_detail t1 left join tbl_commodit_mrch t2 on t1.mrch_id = t2.mrch_id where t1.order_no = ?1";
		Query query = this.entityManager.createNativeQuery(hql);
		query.setParameter(1, orderNo);
		List<Object[]> resultList = query.getResultList();
		List<DTOCommoditOrderDetail> list = new ArrayList<DTOCommoditOrderDetail>();
		if(resultList != null && resultList.size() > 0) {
			for(Object[] obj : resultList) {
				DTOCommoditOrderDetail dto = new DTOCommoditOrderDetail();
				dto.setMrchId("null".equals(String.valueOf(obj[0]))?"":String.valueOf(obj[0]));
				dto.setMrchName("null".equals(String.valueOf(obj[1]))?"":String.valueOf(obj[1]));
				dto.setTermNo("null".equals(String.valueOf(obj[2]))?"":String.valueOf(obj[2]));
				dto.setTermSno("null".equals(String.valueOf(obj[3]))?"":String.valueOf(obj[3]));
				dto.setState(Integer.valueOf(String.valueOf(obj[4])));
				dto.setUpdateTime(String.valueOf(obj[5]));
				dto.setOrderNo(String.valueOf(obj[6]));
				dto.setStateStr(CommoditOrderStatus.getDescByType(dto.getState()));
				String sql = "select t2.name,t2.price,t2.desc,t1.count from tbl_commodit_detail_re t1 left join tbl_commodit t2 on t1.commodit_id = t2.id where order_no = ?1 order by t2.price asc";
				Query q = this.entityManager.createNativeQuery(sql);
				q.setParameter(1, orderNo);
				List<Object[]> resultList2 = q.getResultList();
				StringBuffer sb= new StringBuffer();
				if(resultList2 != null && resultList2.size() > 0) {
					for(Object[] re : resultList2) {
						String name = String.valueOf(re[0]);
						double price = ((double)Long.valueOf(String.valueOf(re[1])))/100;
						String count = String.valueOf(re[3]);
						sb.append(name).append(":").append(price).append("元").append("*").append(count).append("<br/>");
					}
					if(sb.length() > 0) {
						dto.setOrderDetail(sb.substring(0, sb.length()-1));
					}
				}
				if(CommoditOrderStatus.COMMODIT_ORDER_USED.getType() != dto.getState()) {
					dto.setUpdateTime("");
				}
				list.add(dto);
			}
		}
		return list;
	}

	@Override
	public boolean cancelOrder(String orderNo) {
		String sql = "update tbl_commodit_order_detail set state = ?1 where order_no = ?2 and state = ?3";
		Query query = this.entityManager.createNativeQuery(sql);
		query.setParameter(1, CommoditOrderStatus.COMMODIT_ORDER_CANCEL.getType());
		query.setParameter(2, orderNo);
		query.setParameter(3, CommoditOrderStatus.COMMODIT_ORDER_UNUSE.getType());
		return query.executeUpdate() == 1;
	}

}
